package cn.net.vote.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ResourceBundle;

public class RedisUtil {

    public  static  JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool)
    {
        this.jedisPool = jedisPool;
    }
    static {
        //读取配置文件中redis参数
        ResourceBundle resourceBundle = ResourceBundle.getBundle("application");
        int maxActive = Integer.parseInt(resourceBundle.getString("spring.redis.pool.maxActive"));
        int maxIdle = Integer.parseInt(resourceBundle.getString("spring.redis.pool.maxIdle"));
        int maxWait = Integer.parseInt(resourceBundle.getString("spring.redis.pool.maxWait"));
        String ip = resourceBundle.getString("spring.redis.host");
        int port = Integer.parseInt(resourceBundle.getString("spring.redis.port"));

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        jedisPool = new JedisPool(config, ip, port);

    }
    //添加
    public void set(String key, String value){
        Jedis jedis = this.jedisPool.getResource();
        jedis.set(key, value);
        this.jedisPool.returnResource(jedis);
    }

    //添加，带超时时间GenericObjectPool
    public void setex(String key, int seconds, String value){
        Jedis jedis = this.jedisPool.getResource();
        jedis.setex(key, seconds, value);
        this.jedisPool.returnResource(jedis);
    }

    //获取
    public String get(String key){
        Jedis jedis = this.jedisPool.getResource();
        String value = jedis.get(key);
        this.jedisPool.returnResource(jedis);
        return value;
    }

    //查看某个键是否存在
    public boolean exists(String key){
        Jedis jedis = this.jedisPool.getResource();
        Boolean exists = jedis.exists(key);
        this.jedisPool.returnResource(jedis);
        return exists;
    }

    //查看超时时间
    public Long ttl(String key){
        Jedis jedis = this.jedisPool.getResource();
        Long ttl = jedis.ttl(key);
        this.jedisPool.returnResource(jedis);
        return ttl;
    }

    //删除
    public void del(String key){
        Jedis jedis = this.jedisPool.getResource();
        jedis.del(key);
        this.jedisPool.returnResource(jedis);
    }
}